package com.dev.resttemplate.config;

import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName : RestTemplateConfig  //类名
 * @author Administrator
 * @Date: 2021-03-11 09:27  //时间
 */
@Configuration
public class RestTemplateConfig {

    /** 连接池最大连接数 */
    @Value("${httpPoolMaxTotal}")
    private Integer maxTotal;
    /** 每个主机的并发 */
    @Value("${defaultMaxPerRoute}")
    private Integer maxPerRoute;
    /** 读取数据的超时时间 */
    @Value("${readTimeout}")
    private Integer readTimeout;
    /** 客户端和服务器建立连接的超时时间 */
    @Value("${defaultMaxPerRoute}")
    private Integer connectTimeout;
    /** 获取链接超时时间 */
    @Value("${requestTimeout}")
    private Integer requestTimeout;

    @Bean
    public HttpClientConnectionManager poolingConnectionManager() {
        PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
        poolingConnectionManager.setMaxTotal(maxTotal);
        poolingConnectionManager.setDefaultMaxPerRoute(maxPerRoute);
        return poolingConnectionManager;
    }

    @Bean
    public HttpClientBuilder httpClientBuilder() {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //设置HTTP连接管理器
        httpClientBuilder.setConnectionManager(poolingConnectionManager());
        return httpClientBuilder;
    }

    @Bean
    public HttpComponentsClientHttpRequestFactory requestFactory(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setHttpClient(httpClientBuilder().build());
        httpRequestFactory.setConnectionRequestTimeout(requestTimeout);
        httpRequestFactory.setConnectTimeout(connectTimeout);
        httpRequestFactory.setReadTimeout(readTimeout);
        return httpRequestFactory;
    }

    @Bean("restTemplate")
    @LoadBalanced
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(requestFactory());
        return restTemplate;
    }
}
